package com.asen.commons.core.jdbc.builder.mysql;

import com.asen.commons.core.jdbc.builder.SqlBuilder;
import com.asen.commons.core.jdbc.param.ParamStatementSetter;
import com.asen.commons.core.jdbc.param.SqlContext;
import com.asen.commons.core.meta.dao.Condition;
import com.asen.commons.core.meta.loader.EntityObjectLoader;
import com.asen.commons.utils.BaseAssert;

/**
 * 查询构建器
 *
 * @author Gary
 * @version 1.0
 * @date 2018-11-20
 */
public class QueryBuilder implements SqlBuilder {

    private EntityObjectLoader loader = EntityObjectLoader.getInstance();

    private StringBuilder selectSql = new StringBuilder();
    private StringBuilder groupBySql = new StringBuilder();
    private StringBuilder orderBySql = new StringBuilder();
    private StringBuilder limitSql = new StringBuilder();
    private StringBuilder whereSql = new StringBuilder();

    private SqlContext context;

    private boolean buildFlag = false;

    public QueryBuilder(Class<?> modelClazz) {
        this.context = new SqlContext(modelClazz);
    }

    @Override
    public String getSql() {
        BaseAssert.check(buildFlag, "尚未进行SQL构建，不能执行此操作！");
        BaseAssert.check(selectSql.length() > 0, "没有有效的select属性");

        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append(selectSql);
        sql.append(" FROM `").append(context.getMainTable()).append("` _t0");

        sql.append(context.getJoinSql());

        if (whereSql.length() > 0) {
            sql.append(" WHERE ");
            sql.append(whereSql);
        }

        if (groupBySql.length() > 0) {
            sql.append(" GROUP BY ");
            sql.append(groupBySql);
        }

        if (orderBySql.length() > 0) {
            sql.append(" ORDER BY ");
            sql.append(orderBySql);
        }

        if (limitSql.length() > 0) {
            sql.append(" LIMIT ");
            sql.append(limitSql);
        }

        return sql.toString();
    }

    @Override
    public ParamStatementSetter getParams() {
        return context.getParamSetter();
    }

    public void build() throws Exception {
        buildFlag = true;
        SelectBuilder selectBuilder = new SelectBuilder(context);
        selectBuilder.build();
        selectSql = selectBuilder.getSelectSql();
    }

    public void build(Condition condition) throws Exception {
        BaseAssert.notNull(condition, "条件condition不能为空");
        buildFlag = true;

        SelectBuilder selectBuilder = new SelectBuilder(context);
        selectBuilder.build(condition);
        selectSql = selectBuilder.getSelectSql();
        groupBySql = selectBuilder.getGroupBySql();
        orderBySql = selectBuilder.getOrderBySql();
        limitSql = selectBuilder.getLimitSql();

        WhereBuilder whereBuilder = new WhereBuilder(context);
        whereBuilder.build(condition);
        whereSql.append(whereBuilder.getSql());
    }

}
